<?php
include_once('services.filesystem.php');

session_start();

@$id_fsr = $_REQUEST['id_fsr'];

if(empty($id_fsr))
    die('File not found!');

$fs = new FileSystem(CONFIG_FILE);
try
{
    check_admin_rights();

    $tmp_file = tempnam(sys_get_temp_dir(), 'tmp');

    $ok = $fs->zipRepository($id_fsr,$tmp_file);
    
    if(!$ok)
        throw new Exception('Error al crear el zip.');

    $file['mime-type'] = get_mimetype($tmp_file);
    $file['name']      = rand ( 100000 , 999999 ).'.zip';
    $file['length']    = filesize($tmp_file);

    header('Content-Description: File Transfer');
    header('Content-Type:'. $file['mime-type']);
    header('Content-Disposition: attachment; filename='. $file['name'] );
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: '. $file['length']);
    @ob_clean();
    @flush();

    // En este caso al ser los zip archivos normalmente grandes uso "buffered download"
    $total     = filesize($tmp_file);
    $sent      = 0;
    $blocksize = (2 << 20); //2M chunks
    $fp    = fopen($tmp_file, "r");

    // Now we need to loop through the file
    // AND echo out chunks of file data
    WHILE($sent < $total)
    {
        echo fread($fp, $blocksize);
        $sent += $blocksize;
        @flush();
        @ob_flush();
    }

    fclose($fp);
    
    EXIT(0);
    @flush();
    @ob_flush();
}
catch(Exception $e)
{
    print_r($e);
    die("File Not Found");
}

?>